#pragma once
#include<iostream>
#include<vector>
#include<semaphore.h>
using namespace std;
template<class T>
class Ringqueue
{
public:
    Ringqueue(int cap)
    :_max_cap(cap),_rq(_max_cap),_c_step(0),_p_step(0)
    {
       pthread_mutex_init(&_c_mutex,nullptr);
       pthread_mutex_init(&_p_mutex,nullptr);
       sem_init(&_space_sem,0,_max_cap);
       sem_init(&_data_sem,0,0);
    }
    ~Ringqueue()
    {
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);
    }
    void Push(const T& val)
    {
        sem_wait(&_space_sem);
        pthread_mutex_lock(&_c_mutex);
        _rq[_p_step]=val;
        _p_step++;
        _p_step%=_max_cap;
        pthread_mutex_unlock(&_c_mutex);
        sem_post(&_data_sem);
    }
    void Pop(T* out)
    {
        sem_wait(&_data_sem);
        pthread_mutex_lock(&_c_mutex);
       *out=_rq[_c_step];
        _c_step++;
        _c_step%=_max_cap;
        pthread_mutex_unlock(&_c_mutex);
        sem_post(&_space_sem);
    }

private:
    int _max_cap;
    vector<T> _rq;
    int _c_step;
    int _p_step;
    sem_t _space_sem;
    sem_t _data_sem;
    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};